package cn.baddonkey.photography.agent.service.impl;

import cn.baddonkey.photography.agent.config.RedisCache;
import cn.baddonkey.photography.agent.entity.dto.TempSecretDto;
import cn.baddonkey.photography.agent.service.COSService;
import cn.baddonkey.photography.agent.utils.COSUtils;
import com.tencent.cloud.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class COSServiceImpl implements COSService {

    @Autowired
    private COSUtils cosUtils;

    @Autowired
    private RedisCache redisUtil;

    //存储桶 bucket
    @Value("${cos.bucket}")
    private String bucket;

    //储存桶所在地区
    @Value("${cos.region}")
    private String region;

    @Override
    public TempSecretDto getTempSecret() {

        //redis中如果有秘钥，说明上一次生成的秘钥没过期，直接返回
        TempSecretDto record = redisUtil.getCacheObject("cos_temp_secret");
        if (record != null) {
            return record;
        }

        Response response = cosUtils.getTempSecret();
        TempSecretDto tempSecretDto = new TempSecretDto();
        tempSecretDto.setExpiredTime(response.expiredTime);
        tempSecretDto.setStartTime(response.startTime);
        tempSecretDto.setSessionToken(response.credentials.sessionToken);
        tempSecretDto.setTmpSecretId(response.credentials.tmpSecretId);
        tempSecretDto.setTmpSecretKey(response.credentials.tmpSecretKey);
        tempSecretDto.setBucket(bucket);
        tempSecretDto.setRegion(region);
        //按照秘钥有效期作为过期时间，存redis
        redisUtil.setCacheObject("cos_temp_secret", tempSecretDto, COSUtils.durationSeconds, TimeUnit.SECONDS);

        return tempSecretDto;
    }
}
